package net.kazed.nextaction.database.serialize;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Environment;

/**
 * Cursor to query summary of backup files.
 * @author Koert Zeilstra
 */
public class BackupSummaryExternalCursor extends AbstractListCursor {

    public static final int INDEX_ID = 0;
    
    private static final String SUFFIX = ".nab";
    
    private List<SummaryRow> backupFileList;

    /**
     * Constructor.
     */
    private BackupSummaryExternalCursor() {
        super();
        setNumberOfColumns(1);
        addColumnNameMapping(BackupFileSummary.COLUMN_ID, INDEX_ID);
    }
    
    /**
     * Constructor.
     * @param context Android context.
     * @param readContentSummary True if this cursor should read summary information from file.
     */
    public BackupSummaryExternalCursor(Context context) {
        this();
        File externalDir = Environment.getExternalStorageDirectory();
        String[] files = externalDir.list();
        backupFileList = new ArrayList<SummaryRow>(files.length);
        for (int i = 0; i < files.length; i++) {
            String fileName = files[i];
            if (fileName.endsWith(SUFFIX)) {
                String name = fileName.substring(0, fileName.length() - SUFFIX.length());
                try {
                    Long id = Long.parseLong(name);
                    SummaryRow summary = new SummaryRow();
                    summary.createDate = id;
                    backupFileList.add(summary);
                } catch (NumberFormatException e) {
                    // file is not a proper backup file with long ID
                }
            }
        }
        setListSize(backupFileList.size());
    }
    
    @Override
    public long getLong(int columnIndex) {
        long result = 0;
        SummaryRow row = backupFileList.get(getPosition());
        switch(columnIndex) {
        case INDEX_ID:
            result = row.createDate;
            break;
        }
        return result;
    }

    @Override
    public String getString(int columnIndex) {
        String result = null;
        SummaryRow row = backupFileList.get(getPosition());
        switch(columnIndex) {
        case INDEX_ID:
            result = Long.toString(row.createDate);
            break;
        }
        result = backupFileList.get(getPosition()).toString();
        return result;
    }

    /**
     * Row data.
     */
    private static class SummaryRow {
        public long createDate;
    }
    
}
